#!/bin/bash

for dep in `tac /root/script/output-new.txt|awk '{print $1}'`
do
echo "执行工单$dep部署bp-uat环境"
curl -s -u zhang.zhe:tubaobao520zz -X GET -H "Content-Type: application/json" https://jira.ych.com/rest/api/2/issue/$dep|jq .fields.description >/tmp/zz-new
#格式化jira工单的内容格式
sed -i 's!\\r\\n!!g' /tmp/zz-new
sed -i 's!h2.!\n!g' /tmp/zz-new
#sed -i 's! \*\* !,!g' /tmp/zz-new
#sed -i 's! \* ! !g' /tmp/zz-new
#sed -i 's!, !,!g' /tmp/zz-new

#配置文件部分
if [[ `cat /tmp/zz-new|grep application` || `cat /tmp/zz-new|grep "Before Script"` ]];then
    echo "There are configuration file changes, please perform them manually."
    exit 0
fi



#数据库部分
if [[ `cat /tmp/zz-new|grep "DB Migration"` ]];then
  for i in `cat /tmp/zz-new|grep "DB Migration"`
  do 
    db=`echo $i|awk -F "|" '{print $12}'`
    datatag=`echo $i|awk -F "|" '{print $4}'`
    mode=`echo $i|awk -F "|" '{print $8}'`
    echo "synchronize $datatag to $db mode:$mode"
    #curl -X POST -F token=46937f8948aa0a7126e9d0bca0889e" -F ref="lova-dev" -F variables[SERVICE]=$db -F variables[TARGET]="bp-uat" -F variables[MODE]="$mode" -F variables[TAG]="$datatag" "http://10.202.16.73:8900/api/v4/projects/351/trigger/pipeline"
  done
fi

#服务部分
if [[ `cat /tmp/zz-new|grep Service` ]];then
  for svc in `cat /tmp/zz-new|grep Service|awk -F "|" '{for(i=8;i<=NF;i++)if(i%1==0) print $i}'|awk 'NR % 3 == 1'`
  do
     for svctag in `cat /tmp/zz-new|grep Service|awk -F "|" '{for(i=8;i<=NF;i++)if(i%3==0) print $i}'|grep $svc|awk -F ":" '{print $NF}'`
     do
       echo "deploy service: "$svc:$svctag
       #curl -X POST -F token=40afeea2ecef060272d01421a787d1 -F ref="bp-uat" -F variables[SERVICE]=$svc -F variables[TAGS]="$svctag" "http://10.202.16.73:8900/api/v4/projects/119/trigger/pipeline"
     done
  done 
fi

#apk
if [[ `cat /tmp/zz-new|grep "Mobile"` ]];then
  echo "deploy Mobile tag:"$apktag
  apktag=`cat /tmp/zz-new|grep "Mobile"|awk -F "|" '{print $(NF-1)}'`
  #curl -X POST -F token=ea0b992ad48a84b569095d80e1272d  -F ref="release-build" -F variables[env]=bp-uat -F variables[tag]="$tag" "http://10.202.16.73:8900/api/v4/projects/89/trigger/pipeline"
fi

while true
do
  if [[ `kubectl get deployments.apps -n bp-uat|awk '{print $2}'|grep 0` ]];then
    echo "部署中...."
  else
    echo "部署完毕...."
    ssh -o "StrictHostKeyChecking no" root@10.202.16.154 "echo "${dep} has been deployed in bp-uat environment."|mail -s "The\ bp-uat\ environment\ has\ been\ deployed." zhang.zhe@y3.sg,kkarthick@biznessforce.com,"
    #break
    exit 0
  fi
done

#ssh -o "StrictHostKeyChecking no" root@10.202.16.154 "echo "${dep}在lova-qc环境开始部署,请30分钟后尝试使用"|mail -s "lova-qc环境部署完毕" zhang.zhe@y3technologies.com,jingjing.mao@y3technologies.com,sily.zhang@ych.com,jun.chen@ych.com"
done

